package com.ycl.service.impl;

import com.ycl.mapper.HotelMapper;
import com.ycl.pojo.Hotel;
import com.ycl.doc.HotelDoc;
import com.ycl.doc.PageResultDoc;
import com.ycl.pojo.RequestParams;
import com.ycl.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.*;

@Service
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public PageResultDoc search(RequestParams params) {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");

        // 2.准备DSL
        // 2.1 关键字搜索 query
        // 构造booleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key))
            boolQuery.must(QueryBuilders.matchAllQuery());
        else
            boolQuery.must(QueryBuilders.matchQuery("all",key));

        // 城市条件 term
        String city = params.getCity();
        if (city != null && !city.equals(""))
            boolQuery.filter(QueryBuilders.termQuery("city",city));

        // 品牌条件 term
        String brand = params.getBrand();
        if (brand != null && !brand.equals(""))
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));

        // 星级条件 term
        String starName = params.getStarName();
        if (starName != null && !starName.equals(""))
            boolQuery.filter(QueryBuilders.termQuery("starName",starName));

        // 价格过滤 range
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null)
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));

        // 2.2 分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page-1)*size).size(size);

        // 2.3 排序
        String location = params.getLocation();
        if ( location != null && !location.equals("")) {
            request.source()
                    .sort(SortBuilders
                            .geoDistanceSort("location",new GeoPoint(location))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS));
        }

        // 算力控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score数组
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD",true),
                                        //  算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        request.source().query(functionScoreQueryBuilder);

        // 3.发送请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        // 4.解析响应
        return handleResponse(response);
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        // 定义Map
        Map<String,List<String>> map = new HashMap<>();
        // 定义要分类的字段
        String[] filters = {"city","brand","starName"};
        // 准备Request
        SearchRequest request = new SearchRequest("hotel");

        // 构造booleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key))
            boolQuery.must(QueryBuilders.matchAllQuery());
        else
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        // 城市条件 term
        String city = params.getCity();
        if (city != null && !city.equals(""))
            boolQuery.filter(QueryBuilders.termQuery("city",city));
        // 品牌条件 term
        String brand = params.getBrand();
        if (brand != null && !brand.equals(""))
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        // 星级条件 term
        String starName = params.getStarName();
        if (starName != null && !starName.equals(""))
            boolQuery.filter(QueryBuilders.termQuery("starName",starName));
        // 价格过滤 range
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null)
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        // 2.3 排序
        String location = params.getLocation();
        if ( location != null && !location.equals("")) {
            request.source()
                    .sort(SortBuilders
                            .geoDistanceSort("location",new GeoPoint(location))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS));
        }
        request.source().query(boolQuery);

        // 设置size
        request.source().size(0);
        // 循环设置聚合条件
        for (String filterName : filters) {
            request.source().aggregation(
                    AggregationBuilders
                            .terms(filterName+"Agg")
                            .field(filterName)
                            .size(Integer.MAX_VALUE));
        }
        // 发出请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 健壮性判断，如果没有分类数据，则返会null
        if (Objects.isNull(response))
            return null;
        // 获取聚合数据
        Aggregations aggregations = response.getAggregations();
        // 定义List
        List<String> list;
        // 遍历聚合数据
        for (String filterName : filters) {
            // 获取聚合名称
            Terms filterNameAgg = aggregations.get(filterName + "Agg");
            // 获取buckets
            List<? extends Terms.Bucket> buckets = filterNameAgg.getBuckets();
            // 实例list
            list = new ArrayList<>();
            // 遍历 buckets
            for (Terms.Bucket bucket : buckets) {
                String BucketKey = bucket.getKeyAsString();
                // 添加到list
                list.add(BucketKey);
            }
            // 将分类字段与对应集合添加到Map
            map.put(filterName,list);
        }
        return map;
    }

    @Override
    public List<String> getSuggestion(String prefix) {
        // 1. 准备request
        SearchRequest request = new SearchRequest("hotel");
        // 2. 准备DSL
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("suggestions",
                        SuggestBuilders
                                .completionSuggestion("suggestion")
                                .prefix(prefix)
                                .skipDuplicates(true)
                                .size(100)
                ));
        // 3. 发送请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 4. 解析结果
        Suggest suggest = response.getSuggest();
        // 4.1 根据补全结果查询名称，获取补全结果
        CompletionSuggestion completionSuggester = suggest.getSuggestion("suggestions");
        // 4.2 获取options
        List<CompletionSuggestion.Entry.Option> options = completionSuggester.getOptions();
        // 4.3 遍历
        List<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : options) {
            String test = option.getText().toString();
            list.add(test);
        }
        return list;
    }

    @Override
    public void insertById(Long id) {
        try {
            // 0.根据Id查询酒店数据
            Hotel hotel = getById(id);
            if (hotel==null){
                System.out.println("hotel为空");
                return;
            }
            // 转换为HotelDoc对象
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 1.准备Request
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            // 2.准备DSL
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel",id.toString());
            // 3.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private PageResultDoc handleResponse(SearchResponse response) {
        // 4.解析结果
        SearchHits searchHits = response.getHits();
        // 4.1查询总条数
        TotalHits totalHits = searchHits.getTotalHits();
        // 4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.2遍历
        List<HotelDoc> hotels = new ArrayList<>();

        for (SearchHit hit : hits) {
            // 获得文档source
            String json = hit.getSourceAsString();
            // 反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            // 获取排序值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)){
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null){
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮值
                    hotelDoc.setName(name);
                }
            }
            hotels.add(hotelDoc);
        }
        //4.4 封装返回
        return new PageResultDoc(totalHits.value,hotels);
    }
}
